// -*- coding: utf-8 -*-
frappe.ui.form.on('Batch Material List Item', {
    scrap_material: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.scrap_material) {
            // 获取余料信息并填充到子表
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Scrap Material',
                    filters: { name: row.scrap_material },
                    fieldname: ['material_type', 'material_name', 'color', 'length', 'width', 'thickness', 'unit', 'location', 'quantity', 'unit_price']
                },
                callback: function(r) {
                    if (r.message) {
                        frappe.model.set_value(cdt, cdn, 'material_type', r.message.material_type);
                        frappe.model.set_value(cdt, cdn, 'material_name', r.message.material_name);
                        frappe.model.set_value(cdt, cdn, 'color', r.message.color);
                        frappe.model.set_value(cdt, cdn, 'length', r.message.length);
                        frappe.model.set_value(cdt, cdn, 'width', r.message.width);
                        frappe.model.set_value(cdt, cdn, 'thickness', r.message.thickness);
                        frappe.model.set_value(cdt, cdn, 'unit', r.message.unit);
                        frappe.model.set_value(cdt, cdn, 'location', r.message.location);
                        frappe.model.set_value(cdt, cdn, 'available_quantity', r.message.quantity);
                        frappe.model.set_value(cdt, cdn, 'unit_price', r.message.unit_price);
                        
                        // 设置默认数量为可用数量
                        frappe.model.set_value(cdt, cdn, 'quantity', r.message.quantity);
                        
                        // 计算金额
                        let amount = flt(r.message.unit_price) * flt(r.message.quantity);
                        frappe.model.set_value(cdt, cdn, 'amount', amount);
                    }
                }
            });
        }
    },
    
    location: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.location) {
            // 验证库位状态和所属仓库
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Scrap Location',
                    filters: { name: row.location },
                    fieldname: ['status', 'warehouse']
                },
                callback: function(r) {
                    if (r.message) {
                        if (r.message.status !== '启用') {
                            frappe.msgprint({
                                title: '库位状态错误',
                                message: `库位 ${row.location} 状态为 ${r.message.status}，无法使用`,
                                indicator: 'red'
                            });
                            frappe.model.set_value(cdt, cdn, 'location', '');
                            return;
                        }
                        
                        if (frm.doc.warehouse && r.message.warehouse !== frm.doc.warehouse) {
                            frappe.msgprint({
                                title: '仓库不匹配',
                                message: `库位 ${row.location} 属于仓库 ${r.message.warehouse}，与当前仓库 ${frm.doc.warehouse} 不匹配`,
                                indicator: 'red'
                            });
                            frappe.model.set_value(cdt, cdn, 'location', '');
                            return;
                        }
                    }
                }
            });
        }
    },
    
    quantity: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.quantity && row.scrap_material) {
            // 验证数量是否超过可用数量
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Scrap Material',
                    filters: { name: row.scrap_material },
                    fieldname: ['quantity']
                },
                callback: function(r) {
                    if (r.message && flt(row.quantity) > flt(r.message.quantity)) {
                        frappe.msgprint({
                            title: '数量超过可用数量',
                            message: `余料 ${row.scrap_material} 可用数量为 ${r.message.quantity}，不能超过此数量`,
                            indicator: 'red'
                        });
                        frappe.model.set_value(cdt, cdn, 'quantity', r.message.quantity);
                    }
                }
            });
        }
        
        // 计算金额
        if (row.unit_price) {
            let amount = flt(row.unit_price) * flt(row.quantity);
            frappe.model.set_value(cdt, cdn, 'amount', amount);
        }
        
        // 计算总金额
        calculate_total_amount(frm);
    },
    
    unit_price: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        // 计算金额
        if (row.quantity) {
            let amount = flt(row.unit_price) * flt(row.quantity);
            frappe.model.set_value(cdt, cdn, 'amount', amount);
        }
        
        // 计算总金额
        calculate_total_amount(frm);
    },
    
    status: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        // 检查是否所有项都已领料
        check_all_items_issued(frm);
    }
});

// 辅助函数
function calculate_total_amount(frm) {
    let total_amount = 0;
    let total_quantity = 0;
    
    $.each(frm.doc.materials || [], function(i, d) {
        total_quantity += flt(d.quantity);
        total_amount += flt(d.amount);
    });
    
    frm.set_value('total_quantity', total_quantity);
    frm.set_value('total_amount', total_amount);
}

function check_all_items_issued(frm) {
    let all_issued = true;
    $.each(frm.doc.materials || [], function(i, d) {
        if (d.status !== '已领料') {
            all_issued = false;
            return false;
        }
    });
    
    // 如果所有项都已领料，则可以标记为已完成
    if (all_issued && frm.doc.status === '已领料') {
        frm.add_custom_button(__('标记为已完成'), function() {
            mark_as_completed(frm);
        }, __('操作'));
    }
}

// 库位过滤函数
function get_location_filter_for_batch_material_list(frm) {
    return {
        filters: {
            'warehouse': frm.doc.warehouse,
            'status': '启用'
        }
    };
}